package com.wxdc.nmgyt.nmgytwydc.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.wxdc.nmgyt.nmgytwydc.R;
import com.wxdc.nmgyt.nmgytwydc.adapter.WaitCommitData_RecyclerViewAdapter;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.JcdInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.model.BASE_WORKFLOWCURRENT;
import com.wxdc.nmgyt.nmgytwydc.model.COMMIT_AUDIT;
import com.wxdc.nmgyt.nmgytwydc.model.JcdInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.backresult.AuditResultBean;
import com.wxdc.nmgyt.nmgytwydc.model.backresult.AuditRolResultBean;
import com.wxdc.nmgyt.nmgytwydc.model.backresult.ValidateJcdInfoResultBean;
import com.wxdc.nmgyt.nmgytwydc.presenter.AuditPersenter;
import com.wxdc.nmgyt.nmgytwydc.presenter.contract.AuditContract;
import com.wxdc.nmgyt.nmgytwydc.utils.Network;
import com.wxdc.nmgyt.nmgytwydc.utils.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/11/13.
 * 显示待提交数据
 */

public class WaitCommitActivity extends BaseActivity<AuditPersenter> implements AuditContract.View, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.toolbar_title)
    TextView mToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.waitcommit_recyclerview)
    RecyclerView mWaitcommitRecyclerview;
    @BindView(R.id.waitcommit_swrfl)
    SwipeRefreshLayout mWaitcommitSwrfl;
    private List<JcdInfoBean> waitCommitJcdDatas;
    private WaitCommitData_RecyclerViewAdapter mViewAdapter;
    private JcdInfoBean curtSelectJcdInfo;

    @Override
    protected int getLayout() {
        return R.layout.activity_waitcommit;
    }

    @Override
    protected void initInject() {
        getActivityComponent().Inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setSupportActionBar(mToolbar);
        mToolbarTitle.setText(getResources().getString(R.string.manager_01));
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("");
        //设置RecyclerView
        mWaitcommitRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        //设置SwipeRefreshLayout
        mWaitcommitSwrfl.setOnRefreshListener(this);
        mWaitcommitSwrfl.setColorSchemeColors(getResources().getColor(R.color.paleturquoise));
        //解决swipelayout与Recyclerview的冲突
        mWaitcommitRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //计算Recyclerview第一个item的位置是否可见
                int topRowVerticalPosition = (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                // Log.i(TAG, "onScrollStateChanged: -----------" + topRowVerticalPosition +"----------"+recyclerView.getChildCount()+"---------"+recyclerView.getChildAt(0).getTop());
                //当第一个item不可见时，设置SwipeRefreshLayout不可用
                mWaitcommitSwrfl.setClickable(topRowVerticalPosition == 0);
            }
        });
        if (waitCommitJcdDatas == null) {
            waitCommitJcdDatas = new ArrayList<>();
        }
    }

    //打开当前页面
    public static void startActivity(Context context) {
        Intent intent = new Intent(context, WaitCommitActivity.class);
        context.startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int selectId = item.getItemId();
        switch (selectId) {
            case android.R.id.home:
                this.finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 初始化所需要数据
     */
    private int curtIndex;
    private List<JcdInfoBean> unJcdList;

    private void initData() {
        if (!Network.isConnected(mContext)) {
            mApp.showToastLongMessage(mContext, getResources().getString(R.string.no_network));
            mWaitcommitSwrfl.setRefreshing(false);
            return;
        }
        waitCommitJcdDatas.clear();
        unJcdList = JcdInfoBeanDaoOpe.queryForUnCommitJcdData(mContext, SharedPreferenceUtil.getGzdwdm());
        curtIndex = 0;
        mCircleProgressDialog.showDialog();
        mPersenter.validateIsYdInfo(unJcdList.get(curtIndex).getGEMPOINTID());

    }

    /**
     * 显示未提交数据
     */
    private void updataUI() {
        if (mViewAdapter == null) {
            mViewAdapter = new WaitCommitData_RecyclerViewAdapter(mContext, waitCommitJcdDatas);
            mWaitcommitRecyclerview.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));//添加默认分割线
            mWaitcommitRecyclerview.setAdapter(mViewAdapter);
            mViewAdapter.setOnClickListener(new WaitCommitData_RecyclerViewAdapter.RcyclerViewOnClickListener() {
                @Override
                public void onClick(View view) {
                    int position = (int) view.getTag();
                    switch (view.getId()) {
                        case R.id.wcr_rv_item_commit_txt:
                            //mApp.showToastLongMessage(mContext,"提交审核");
                            curtSelectJcdInfo = waitCommitJcdDatas.get(position);
                            commitAuditFunc();
                            break;
                        default:
                            //mApp.showToastLongMessage(mContext,"点击查看详情");
                            EventBus.getDefault().postSticky(waitCommitJcdDatas.get(position));
                            WebActivity.start(mContext, "file:///android_asset/MobileT_Yd.html", "ydinfo");
                            break;
                    }
                }
            });
        } else {
            mViewAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 提交审核
     */
    private AlertDialog commitDialog;

    private void commitAuditFunc() {
        commitDialog = new AlertDialog.Builder(mContext)
                .setMessage(curtSelectJcdInfo.getGEMNAME() + "(" + Calendar.getInstance().get(Calendar.YEAR) + " 数据)")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (commitDialog != null) {
                            commitDialog.dismiss();
                        }
                    }
                })
                .setPositiveButton("提交", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (commitDialog != null) {
                            commitDialog.dismiss();
                        }
                        if (!Network.isConnected(mContext)) {
                            mApp.showToastLongMessage(mContext, getResources().getString(R.string.no_network));
                            return;
                        }
                        mCircleProgressDialog.showDialog();
                        mPersenter.getUserAuditRol();//获得权限
                    }
                }).create();
        commitDialog.show();
    }

    @Override
    public void onRefresh() {
        initData();
    }

    @Override
    public void showError(String msg) {
        mApp.showToastLongMessage(mContext, msg);
        if (mWaitcommitSwrfl != null) {
            mWaitcommitSwrfl.setRefreshing(false);
        }
        hideProgressDialog();
    }


    /**
     * 获取当前用户的审核权限
     */
    @Override
    public void userAuditRolResult(List<AuditRolResultBean> resultBeans) {
        if (resultBeans != null) {
            int len = resultBeans.size();
            for (int i = 0; i < len; i++) {
                if (resultBeans.get(i).getAUDITSTATEDM().equals("1003")) {
                    COMMIT_AUDIT commit_audit = new COMMIT_AUDIT();
                    commit_audit.setWFSTATE("1");
                    commit_audit.setGEMPOINTID(curtSelectJcdInfo.getGEMPOINTID());
                    commit_audit.setSAMPLEPLOTID(curtSelectJcdInfo.getGEMPOINTID() + "-" + Calendar.getInstance().get(Calendar.YEAR));
                    commit_audit.setGEMNAME(curtSelectJcdInfo.getGEMNAME());
                    commit_audit.setAUDITROLEID(resultBeans.get(i).getAUDITRANKDM());
                    commit_audit.setAUDITSTATEDM(resultBeans.get(i).getAUDITSTATEDM());
                    commit_audit.setAUDITSTATE(resultBeans.get(i).getAUDITSTATENAME());
                    commit_audit.setAUDITIDEA("");
                    commit_audit.setAUDITFEILD("");
                    commit_audit.setFLOWNODEID("");
                    commit_audit.setVERSION("");
                    mPersenter.commitAudit(commit_audit);//向服务器提交审核
                }
            }
        }
    }

    @Override
    public void getAuditDataResult(List<BASE_WORKFLOWCURRENT> results) {

    }

    @Override
    public void getBackOrWaitAuditDataResult(List<BASE_WORKFLOWCURRENT> results) {

    }

    /**
     * 提交审核返回结果
     *
     * @param resultBean
     */
    @Override
    public void getCommitAuditResult(AuditResultBean resultBean) {
        mCircleProgressDialog.dismiss();
        if ("200".equals(resultBean.getCode()) && resultBean.getUs().equals("0")) {
            mApp.showToastLongMessage(mContext, resultBean.getReMessage());
            curtSelectJcdInfo.setAuditFlag(1);
            JcdInfoBeanDaoOpe.updateData(mContext, curtSelectJcdInfo);
            initData();
        } else {
            mApp.showToastLongMessage(mContext, resultBean.getReMessage());
        }
    }

    @Override
    public void getYdInfoValidateResult(ValidateJcdInfoResultBean obj) {
        JcdInfoBean mjcdObj = unJcdList.get(curtIndex);
        if ("200".equals(obj.getCode()) && !obj.getReRows().equals("0")) {//已采集数据
            mjcdObj.setAuditFlag(2);
            waitCommitJcdDatas.add(mjcdObj);
        }
        curtIndex++;
        if (curtIndex < unJcdList.size()) {
            mPersenter.validateIsYdInfo(unJcdList.get(curtIndex).getGEMPOINTID());
        } else {
            updataUI();
            mCircleProgressDialog.dismiss();
            if (mWaitcommitSwrfl != null) {
                mWaitcommitSwrfl.setRefreshing(false);
            }
        }
    }

    //===========================================================================================

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
